<template>
	<view >
	<!-- 404页面 -->
        <view class="noData" v-if="netWorkType == 'none'"><noData @handle="refresh"></noData></view>
        <view v-if="netWorkType != 'none'">
			<tui-skeleton v-if="skeletonShow" backgroundColor="#fafafa"></tui-skeleton>
			<view  class="container content tui-skeleton" v-if ="data.list.length>0">
				
				<view class="order-list" v-for="item in data.list" >
					<view class="img">
						<image :src="item.cover_image" mode="aspectFit "></image>
					</view>
					
					<view class="product-box">
						<view class="title">
							{{item.name}}
						</view>
						<view class="norms">
							规格：{{item.item_name||'默认'}}
						</view>
						<view class="price-box">
							<view class="price">
								￥<text class="big-text">{{item.price||'--'}}</text>
							</view>
							<view class="btn" @tap="addCart(item)">
								再次购买
							</view>
						</view>
					</view>
					
				</view>
				
				
			</view>	
			<view class="container content tui-skeleton" v-else>
				<view class="no-order" >
					<view class="img">
						<image :src="OSS_HOST+'img/cart-nogoods.png'" mode=""></image>	
					</view>
					<view class="to-list" @tap="toclass">
						什么都没有，快去逛逛吧！
					</view>
					
				</view>
			</view>
			<view class="cart" @tap.stop="tocart">
				<text class="iconfont">&#xe649;</text>
				<text class="number">{{product_type_num}}</text>
			</view>
			
			<!-- 登录弹框 -->
			<uni-popup-vlogin id="popupvLogin" ref="popupvLogin" type="bottom"/>
			<!-- 提示弹框 -->
			<tui-tips ref="toast"></tui-tips>
		</view>			
	</view>
</template>

<script>
	import {oss_host} from '@/config/config.js';	
	
	// 推广名片
	// import _app from '@/js_sdk/QuShe-SharerPoster/util/QS-SharePoster/app.js';
	// import {
	// 		getSharePoster
	// 	} from '@/js_sdk/QuShe-SharerPoster/util/QS-SharePoster/QS-SharePoster.js';
	
	// import he from '@/utils/he.js'
	import cart from '@/utils/cartshop.js' ;
	import { mapGetters } from 'vuex';
	export default {
		data() {
			return {
				skeletonShow:true,
				data:{
					list:[
						
					],
					userList:[],
					order:[],
					award:'0.00',
					count:"",
					dayCount:'',
					monthCount:'',
					used_estate:true,
					free_day:0,
					user:[]
				},
				// 推广名片
				hasLogin:false,
				poster: {},
				qrShow: false,
				canvasId: 'default_PosterCanvasId',
				
				// 列表头部
				record:['邀请注册','消费金额'],
				// 判断
				recordNum:0,
				//生成二维码地址
				qrImgHost:'',
				// 节点
				OSS_HOST:oss_host,
				rule:'',
				page:0,
				lastPage:0,
				cartList:{},
				product_num:0,
				product_type_num:0,
			};
		},
		components: {
			
		},
		computed: {
		    ...mapGetters(['netWorkType'])    
		},
		onLoad() {
			
			// this.qrImgHost = this.$service.getQrImgHost()
			
			
			
		},
		onShow:function() {
			this.getList()
			this.cartList = uni.getStorageSync('cartList')==''?{}:JSON.parse(uni.getStorageSync('cartList'))
		},
		watch:{
			cartList:{
				handler(newGoodslist,oldval){
					
					let num = 0
					let product_number = 0
					let amount = 0
					// 格式问题无法使用foreach
					for(let key in newGoodslist){
						// this.cartList[key].check = _this.batchCartList[key].check
						for(let key1 in newGoodslist[key].goodslist){
							amount += (newGoodslist[key].goodslist[key1].price*newGoodslist[key].goodslist[key1].number)				
							product_number +=newGoodslist[key].goodslist[key1].number
							num  +=1
							newGoodslist[key].goodslist[key1].check = true
						}
					}
					
					// this.amount=amount.toFixed(2) //累计金额
					this.product_type_num=num//种类数量
					this.product_num=product_number//产品数量
					
					
					
					console.log('watch payCartList change')
					// this.payAmount = 0
					// for(let key in newGoodslist){
					// 	this.cartList[key].check = newGoodslist[key].check
					// 	for(let key1 in newGoodslist[key].goodslist){
					// 		this.payAmount += (newGoodslist[key].goodslist[key1].price*newGoodslist[key].goodslist[key1].number)				
					// 		this.cartList[key].goodslist[key1].check = true
					// 	}
					// }
				},
				immediate:true,
				deep:true
				
			},
			immediate:true,
			deep:true
		},
		methods:{
			// 刷新的方法
			refresh(){
			   // window.addEventListener('pageshow', this.onShow);     
				this.getList()
			},
			onReachBottom(){
				 // 分页 上拉加载
			  if (this.page >= this.lastPage) {
					// console.log(1111111)
			  	uni.showToast({
			  		icon: 'none',
			  		title: '没有更多数据'
			  	});
			  	return;
			  }
			  
			  this.getList();
			  
			},
			toclass(){
					   let _this = this
					   _this.$refer.setVilit('/pages/SearchGoodsList/SearchGoodsList')
					   let callback = function(url) {
					   	_this.$refs.popupvLogin.open()
					   }
					   let data = {
					   
					   	
					   }
					   _this.$refer.toUrl(callback, data)
						// uni.switchTab({
						// 	url:'/pages/classify/classify',
						// 	success: (res) => {
						// 				let page = getCurrentPages().pop();
						// 				if (page == undefined || page == null) return;
						// 				page.curSegment = 0;
						// 				page.onLoad();
						// 			},
						// })
			},
			tocart(){
				uni.switchTab({
					url:'/pages/cart/cart',
					success: (res) => {
								let page = getCurrentPages().pop();
								if (page == undefined || page == null) return;
								page.curSegment = 0;
								page.onLoad();
								page.onShow();
							},
				})
			},
			// 初次进入
			getList(){
				// 获取初始列表
				let _this=this;
				var opt={
						url:'/product/historyList',
						data:{
							page:++_this.page
						},
						success:function(res){
							console.log(res)
							if(res.status==1){
								_this.skeletonShow =false
								_this.lastPage = res.data.last_page
								// _this.data.list = res.data.list
								if(_this.page == 1){
									_this.data.list = res.data.list
								}else{
									_this.data.list =_this.data.list.concat(res.data.list) 
								}
								
								
							}else{
								  let options = {
									msg: res.message,
									type:'danger'
								  };								
								_this.$refs.toast.showTips(options);
							
							}
						}
				};
				_this.$service.GetApi(opt); 
			},
			// 切换
			Record(index){
				// console.log('****',index)
				this.recordNum=index
				// if(index){
				// 	this.data.list = this.data.order
				// }else{
				// 	this.data.list = this.data.userList
				// }
				// this.$forceUpdate()
				// this.getList()
			},
			toList(type){
				if(type=='more'){
					const _this = this
					_this.$refer.setVilit('/packageUser/pages/user/promotion/statistics/invite_record')
					let callback = function(url){
					   _this.$refs.popupvLogin.open()
					}
					_this.$refer.toUrl(callback)
					return
				}
				
			},
			addCart(item){
				let _this = this
				if(item.is_del==1){
					uni.showToast({
						icon:'none',
						title:'产品已下架'
					})
					return ;
				}
				uni.showModal({
				  title: '确认操作',
				  content: '确认加入购物车',
				  success (res) {
				    if (res.confirm) {
				      console.log('用户点击确定')
					  let goods2 = {
					  	product_id:item.id,
					  	norms_value_id:item.item_id,
					  	store_id:item.store_id,
					  	store_name:item.store_name,
					  	product_name:item.name,
					  	norms_name:item.item_name,
					  	price:item.price,
					  	number:1,
					  	src:item.cover_image,
					  }
					// console.log(goods2,_this.cartList);
					  // if(this.cartList[goods2.store_id]?.goodslist[goods2.norms_value_id] ){  
					  // 	let cartnumber = this.cartList[goods2.store_id].goodslist[goods2.norms_value_id].number;
					  // 	// if(this.limitInfo.limit_num > 0 && cartnumber+this.num > this.limitInfo.limit_num){
					  // 	// 	this.cartList[goods2.store_id].goodslist[goods2.norms_value_id].number = this.limitInfo.limit_num-this.num;
					  // 	// }
					  // }
					    cart.add(goods2,_this.cartList,(res)=>{
					       console.log(res)
					       uni.setStorageSync('cartList',JSON.stringify(res.data.cartList))
					     });
						 console.log(uni.getStorageSync('cartList'),'*****c')
						 uni.showToast({
						 	icon:'none',
							title:'操作成功'
						 })
				    } else if (res.cancel) {
				      console.log('用户点击取消')
				    }
				  }
				})
				
				
				
				
			},
			rules(){
				// 打开弹框
			this.$refs.rulesPopup.open()
			},
			// 推广名片
			shareFc(){
				let _this=this;
				_this.$refer.setVilit('/packageUser/pages/my/qrcode/qrcode')
				let callback = function(url){
				   _this.$refs.popupvLogin.open()
				}
				_this.$refer.toUrl(callback)
				// let _this=this;
				// var opt={
				// 		url:'/Promotion/insertEnter',
				// 		data:{
											
				// 		},
				// 		success:function(res){
									
				// 			if(res.status==1){   			  				 
				// 				_this.createImg(res.data.uid,res.data.nickname,res.data.avatar)																						
				// 			}else{
				// 					uni.showToast({
				// 						icon:'none',
				// 						title:res.message
				// 					});
				// 			}
				// 		}
				// };
				
				// _this.$service.GetApi(opt); 
			},
			async createImg(uid,nickname,avatar) {
				try {
					//console.log('准备生成:' + new Date())
					const d = await getSharePoster({
						_this: this, //若在组件中使用 必传
						type: 'server',
						posterCanvasId: this.canvasId,	//canvasId
						delayTimeScale: 20, //延时系数
						/* background: {
							width: 1080,
							height: 1920,
							backgroundColor: '#666'
						}, */
						drawArray: ({
							bgObj,
							type,
							bgScale
						}) => {
							const dx = bgObj.width * 0.5;
							const fontSize = bgObj.width * 0.045;
							const lineHeight = bgObj.height * 0.04;
							//可直接return数组，也可以return一个promise对象, 但最终resolve一个数组, 这样就可以方便实现后台可控绘制海报
							return new Promise((rs, rj) => {
								rs([
									// {
									// 	type: 'custom',
									// 	setDraw(Context) {
									// 		Context.setFillStyle('black');
									// 		Context.setGlobalAlpha(0.3);
									// 		Context.fillRect(0, bgObj.height - bgObj.height * 0.2, bgObj.width, bgObj.height * 0.2);
									// 		Context.setGlobalAlpha(1);
									// 	}
									// },
									{
										type: 'image',
										url: avatar,
										alpha: 1,
										dx:bgObj.width-670,
										dy:bgObj.height- bgObj.width*1.16,
										infoCallBack(imageInfo) {
											let scale = bgObj.width * 0.1 / imageInfo.height;
											return {
												circleSet: {
													x: imageInfo.width * scale / 2,
													y: bgObj.width * 0.1 / 2,
													r: bgObj.width * 0.1 / 2
												}, // 圆形图片 , 若circleSet与roundRectSet一同设置 优先circleSet设置
												dWidth: imageInfo.width * scale, // 因为设置了圆形图片 所以要乘以2
												dHeight: bgObj.width * 0.1,
												/* roundRectSet: { // 圆角矩形
													r: imageInfo.width * .1
												} */
											}
										}
									},
									{
										type: 'text',
										fontStyle: 'italic',
										text: nickname,
										size: fontSize,
										color: 'white',
										alpha: 1,
										lineFeed: {
										        maxWidth: 150,
										        lineHeight: 50,
										        lineNum: -1,
										        dx: -1
										    },
										textAlign: 'left',
										textBaseline: 'middle',
										infoCallBack(textLength) {
											//_app.log('index页面的text的infocallback ，textlength:' + textLength);
											return {
												dx: bgObj.width-588,
												dy: bgObj.height- bgObj.width*1.109
											}
										},
										serialNum: 0,
										id: 'tag1'	//自定义标识
									},
									{
										type: 'qrcode',
										text: this.qrImgHost+'/wechat/promotion/param/?promotion_id='+uid,
										size: bgObj.width * 0.47,
										dx: bgObj.width * 0.286,
										dy: bgObj.height - bgObj.width * 0.775
									}
								]);
							})
						},
						setCanvasWH: ({
							bgObj,
							type,
							bgScale
						}) => { // 为动态设置画布宽高的方法，
							this.poster = bgObj;
						}
					});
					//console.log('海报生成成功, 时间:' + new Date() + '， 临时路径: ' + d.poster.tempFilePath)
					this.poster.finalPath = d.poster.tempFilePath;
					this.qrShow = true;
				} catch (e) {
					_app.hideLoading();
					_app.showToast(JSON.stringify(e));
					console.log(JSON.stringify(e));
				}
			},
			hideQr() {
				this.qrShow = false;
			},
			
			
	
		}
	}
</script>

<style lang="scss">
	 @import "./index.scss";
</style>
